/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utilitario;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JPasswordField;

/**
 *
 * @author HERNAN
 */
public class JPasswordFieldChanged extends JPasswordField {

	private static final long serialVersionUID = 1L;
    JPasswordField textoBorde;
    int numCar;

    public JPasswordFieldChanged(int parNumCar) {

        super.setDisabledTextColor(Color.BLACK);
        textoBorde = new JPasswordField(parNumCar);
        this.numCar = parNumCar;

        super.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                JPasswordField control = (JPasswordField) evt.getSource();
                if (control.isEnabled()) {

                    control.setBorder(textoBorde.getBorder());
//                    control.setBackground(Color.WHITE);
                    control.setOpaque(true);

                } else if (!control.isEnabled()) {

                    control.setBorder(javax.swing.BorderFactory.createEtchedBorder());
                    control.setBackground(textoBorde.getBackground());
                    control.setOpaque(false);

                }
            }
        });

        super.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {

                JPasswordField control = (JPasswordField) e.getSource();
                control.setBackground(Color.YELLOW);
                control.setOpaque(true);

            }

            @Override
            public void focusLost(FocusEvent e) {

                JPasswordField control = (JPasswordField) e.getSource();
                control.setBackground(Color.WHITE);
                control.setOpaque(true);

            }
        });
        super.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {

                JPasswordField control = (JPasswordField) e.getSource();
                if (control.getText().trim().length() >= numCar
                        || (e.getKeyCode() == KeyEvent.VK_SPACE && control.toString().trim().length() >= numCar)) {

//                    System.out.println("ttecto  " + control.getText().trim() + this.getClass().getName());
//                    control.setText(control.toString().trim().substring(0, numCar));
                    e.consume();

                }
            }//Fin de metodo keyTyped
        });
    }//Fin de Constructor
}